<?php

// +----------------------------------------------------------------------
// | Apprh.Shop
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2027 http://www.apprh.com All rights reserved.
// +----------------------------------------------------------------------
// | Notice: This code is not open source, it is strictly prohibited
// |         to distribute the copy, otherwise it will pursue its
// |         legal responsibility.
// +----------------------------------------------------------------------
// | Author: 
// +----------------------------------------------------------------------

namespace app\admin\controller;

use controller\BasicAdmin;
use service\DataService;
use service\ToolsService;
use service\LogService;
use think\Db;

/**
 * 系统用户管理控制器
 * Class User
 * @package app\admin\controller
 * @author 
 * @date 2017/02/15 18:12
 */
class User extends BasicAdmin
{

    /**
     * 指定当前数据表
     * @var string
     */

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 用户列表
     */
    public function index()
    {
        $this->title = '系统用户管理';
        $get = $this->request->get();
        // $aid = session('user.fp_affiliated_area');
        // $areas = Db::name('area')->order('area_id asc')->select();
        // $aid = ToolsService::arr2table($aid, 'id', 'pid');
        // $aid = $this->_getAreaTrees();
        // halt($this->aids);
        $db = $this->SU->where([
            // 'status' => 1,
            // 'id' => ['neq', 1],
            'is_deleted' => '0',
            'aid' => ['in', $this->aids],
            'id' => ['notin', '1,'.session('user.id')],
            ]);
        foreach (['username', 'phone', 'email', 'aid', 'authorize'] as $key) {
            if (isset($get[$key]) && $get[$key] !== '') {
                if($key == 'aid'){
                    $areas = $this->AR->order('area_id asc')->select();
                    $aids = ToolsService::getArrSubIds($areas,$get[$key],'area_id','area_parent_id');//当前区域下地区Ids
                    $db->where($key, 'in', $aids);
                }elseif($key == 'authorize'){
                    if($get[$key] == 'a'){//主管用户数
                        $db->where(function ($query) {
                            $query->where('authorize', ['like',"%2%"],['like',"%4%"],['like',"%6%"],['like',"%8%"],'or');
                        });
                    }
                    if($get[$key] == 'b'){//服务商用户数
                        $db->where(function ($query) {
                            $query->where('authorize', ['like',"%3%"],['like',"%5%"],['like',"%7%"],['like',"%9%"],'or');
                        });
                    }
                    if($get[$key] == 'c'){//企业用户数
                        $db->where(function ($query) {
                            $query->where('authorize', ['like',"%10%"],'or');
                        });
                    }
                    if($get[$key] == 'd'){//电商扶贫示范户用户数
                        $db->where(function ($query) {
                            $query->where('authorize', ['like',"%11%"],'or');
                        });
                    }
                    if($get[$key] == 'e'){//建档立卡扶贫示范户用户数
                        $db->where(function ($query) {
                            $query->where('authorize', ['like',"%12%"],'or');
                        });
                    }
                }else{
                    $db->where($key, 'like', "%{$get[$key]}%");                 
                }
            }
        }
        
        $areaList = $this->_getAreaTrees('Area', ['area_open' => 1, 'area_id' => ['in', $this->aids]]);
        $this->assign('areaList', $areaList);
        // halt($areaList);

        return parent::_list($db);
    }

    /**
     * 授权管理
     * @return array|string
     */
    public function auth()
    {
        return $this->_form($this->SU, 'auth');
    }

    /**
     * 用户添加
     */
    public function add()
    {
        return $this->_form($this->SU, 'form');
    }

    /**
     * 用户编辑
     */
    public function edit()
    {
        return $this->_form($this->SU, 'form');
    }

    /**
     * 用户密码修改
     */
    public function pass()
    {
        if ($this->request->isGet()) {
            $this->assign('verify', false);
            return $this->_form($this->SU, 'pass');
        }
        $data = $this->request->post();
        if ($data['password'] !== $data['repassword']) {
            $this->error('两次输入的密码不一致！');
        }
        if (DataService::save($this->SU, ['id' => $data['id'], 'password' => md5($data['password'])], 'id')) {
            LogService::write('系统用户', '系统用户密码修改成功');
            $this->success('密码修改成功，下次请使用新密码登录！', '');
        }
        $this->error('密码修改失败，请稍候再试！');
    }

    /**
     * 表单数据默认处理
     * @param array $data
     */
    public function _form_filter(&$data)
    {
        if ($this->request->isPost()) {
            // halt($data);
            if (isset($data['authorize']) && is_array($data['authorize'])) {
                $data['authorize'] = join(',', $data['authorize']);
            }
            if (isset($data['username']) && strlen($data['username']) < 4) {
                $this->error('账号长度不能少于6位有效字符!');
            }
            // if (empty($data['bgd_name'])) {
            //     $this->error('请填写大数据平台账号');
            // }
            if(!empty($data['password']) || !empty($data['repassword'])){                
                if (strlen($data['password']) < 4 || strlen($data['repassword']) < 4) {
                    $this->error('密码长度不能少于6位有效字符!');
                }
                if ($data['password'] != $data['repassword']) {
                    $this->error('密码不一致!');
                }
                $data['password'] = md5($data['password']);
            }else{
                unset($data['password']);
            }
                unset($data['repassword']);
            if (empty($data['aid'])) {
                $this->error('请选择地区');
            }
            // if (empty($data['fp_affiliated_area'])) {
            //     $this->error('请选择扶贫地区');
            // }
            if (isset($data['id'])) {
                LogService::write('系统用户', '系统用户修改成功');
                unset($data['username']);
            } elseif ($this->SU->where(['username' => $data['username']])->find()) {
                $this->error('用户账号已经存在，请使用其它账号！');
            }else{
                LogService::write('系统用户', '系统用户添加成功');
            }
        } else {

            //获取地区
            $areaList = $this->_getAreaTrees('Area', ['area_open' => 1, 'area_id' => ['in', $this->aids]]);
            $this->assign('areaList', $areaList);
            $aut = isset($data['authorize']) ? $data['authorize'] : '';
            $data['authorize'] = explode(',', $aut);
            // $authIds = cate_auth_chunk($this->aid);
            // halt($authIds);
            // halt($data['authorize']);
            // $map = ['id' => ['gt', $authIds[0]]];
            // if($aut == (3 || 5)){//如果是市级服务商，跳到下级
            //     $map = ['id' => ['gt', $authIds[1]]];
            // }else{
            //     $map = ['id' => ['gt', $authIds[0]]];
            // }
            // elseif($aut == 5){//如果是县级服务商，跳到下级
            //     $map = ['id' => ['gt', $authIds[1]]];
            // }
            // $map = (($aut == 3) || ($aut ==  5)) ? ['id' => ['gt', $authIds[1]]] : ['id' => ['gt', $authIds[0]]];//如果是市/县级【服务商】，跳到下级
            // $map = ['id' => ['gt', $authIds[1]]];
            // // halt($map);
            // $area = db('Area')->where(['area_id' => $this->aid])->find();
            // if($area['area_deep'] > 2){//如果是县级【服务商】以下，只能选取县级以下角色授权
            //     $map = ['id' => ['between', [$authIds[0], 9]]];
            // }
            // halt($map);
            $this->assign('authorizes', Db::name('SystemAuth')->where(['id' => ['neq', 1]])->select());
        }
    }

    /**
     * 删除用户
     */
    public function del()
    {
        if (in_array('1', explode(',', $this->request->post('id')))) {
            $this->error('系统超级账号禁止删除！');
        }
        if (DataService::update($this->SU)) {
            LogService::write('系统用户', '系统用户删除成功');
            $this->success("用户删除成功！", '');
        }
        $this->error("用户删除失败，请稍候再试！");
    }

    /**
     * 用户禁用
     */
    public function forbid()
    {
        if (in_array('1', explode(',', $this->request->post('id')))) {
            $this->error('系统超级账号禁止操作！');
        }
        if (DataService::update($this->SU)) {
            LogService::write('系统用户', '系统用户禁用成功');
            $this->success("用户禁用成功！", '');
        }
        $this->error("用户禁用失败，请稍候再试！");
    }

    /**
     * 用户禁用
     */
    public function resume()
    {
        if (DataService::update($this->SU)) {
            LogService::write('系统用户', '系统用户启用成功');
            $this->success("用户启用成功！", '');
        }
        $this->error("用户启用失败，请稍候再试！");
    }

}
